<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
const {proxy} = getCurrentInstance();
import {
  createForm,
  selectFormById,
  updateFormById,
  moduleTypes,
  modulePlugs
} from "@/api/basal.js";
import {ResultEnums} from "@/enums/ResultStatusEnums.js";
import {useRouter} from "vue-router";
const router = useRouter();
const formRef = ref(null)
const errorMessage = ref(null)
const form = reactive({createSystemCode: proxy.$route.query.systemCode,isEnable:true, id:proxy.$route.query.id,sort:0,
  fieldName:'',fieldCode:'',fieldType:'',limitValue:'',allowEmpty:false,allowDesign:true,moduleName:proxy.$route.query.moduleName,checkPlugs:[]});
const historyFieldType = ref('')
onMounted(() => {
   searchModuleTypes().then(data => {
     types.value = data
     for(let index in data){
       examples[data[index].key]=data[index].example
     }
   });
  onLoad( proxy.$route.query.systemCode,proxy.$route.query.id).then(data => {
    for(const key in data){
       form[key] = (key === 'checkPlugs' && !data[key] )?[]:data[key]
    }
    historyFieldType.value = form.fieldType
    onLoadPlugs(data.moduleName,data.fieldType,data.id);
    checkSelect.value = form.fieldType
    shouldValue.value = form.limitValue
    checkInput();
  });
})
const types = ref([])
const examples = reactive({})
const checkSelect = ref('')
const shouldValue = ref('')
const transformShouldValue = ref()
const structError = ref(false)
const plugs = ref([])
async function onLoad(systemCode,id){
  let data = []
  if(id && systemCode){
    let result = await selectFormById(systemCode,id);
    if(result.code === ResultEnums.SUCCESS ){
      data = result.data
    }
  }
  return data
}

async function searchModuleTypes(){
  const result = await moduleTypes();
  return result.code === ResultEnums.SUCCESS? result.data : []
}

async function onLoadPlugs(moduleName,moduleType,formId){
  let data = []
  if(moduleName && moduleType){
    const result = await modulePlugs(proxy.$route.query.systemCode,moduleName,moduleType,formId)
    data = result.code === ResultEnums.SUCCESS?result.data: []
  }
  plugs.value = data
}

async function selectChange(moduleName,moduleType,formId){
  await onLoadPlugs(moduleName,moduleType,formId)
  checkSelect.value = moduleType
  if(historyFieldType.value === moduleType ){
    shouldValue.value = form.limitValue
    await checkInput()
  } else {
    transformShouldValue.value = ''
    shouldValue.value = ''
  }
}

async function notAllowEmptyCheck(){
  const value = form.allowEmpty
  if(value) form.allowEmpty = false
}

function confirm(e){
  e.preventDefault();
  if (formRef.value.checkValidity() && !structError.value) {
    errorMessage.value = false
    if(form.id){ invokeUpdate(form.createSystemCode,form.id,form)} else { invokeInsert(form) }
  } else {
    formRef.value.reportValidity();
  }
}

async function invokeInsert(obj){
  const result = await createForm(obj)
  if(result.code === ResultEnums.SUCCESS ){
    router.go(-1);
  }else {
    errorMessage.value = result.message;
  }
}

async function invokeUpdate(systemCode,id,obj){
  const result = await updateFormById(systemCode,id,obj)
  if(result.code === ResultEnums.SUCCESS ){
    router.go(-1);
  }else {
    errorMessage.value = result.message;
  }
}

async function checkInput(){
  try {
    structError.value = false
    const value = JSON.parse(shouldValue.value||'{}')
    switch (checkSelect.value) {
      case '03':
        // 数字输入框
        const keys = Object.keys(value)
        if(keys.length === 2 && keys.includes('max','min')){
          const min = value.min
          const max = value.max
          if(min > max){
            structError.value = true
          }else {
            transformShouldValue.value = value
            form.limitValue = shouldValue.value
          }
        } else {
          structError.value = true
        }
        break;
      case '05':
        // 复选框
        if(Array.isArray(value)){
          structError.value = true
        }else {
          transformShouldValue.value = value
          form.limitValue = shouldValue.value
        }
        break;
      case '06':
        // 单选框
        if(Array.isArray(value)){
          structError.value = true
        }else {
          transformShouldValue.value = value
          form.limitValue = shouldValue.value
        }
        break;
      case '07':
        // 数字滑块框
        const rangeKeys = Object.keys(value)
        if(rangeKeys.length === 2 && rangeKeys.includes('max','min')){
          const min = value.min
          const max = value.max
          if(min > max){
            structError.value = true
          }else {
            transformShouldValue.value = value
            form.limitValue = shouldValue.value
          }
        } else {
          structError.value = true
        }
        break;
      default:
        structError.value = false
        transformShouldValue.value = value
        form.limitValue = shouldValue.value
    }
  }catch(error){
    console.log(error)
    structError.value = true
  }
}
</script>

<template>
  <h1 class="app-page-title" v-if="proxy.$route.meta">
    <a href="#" @click="(e)=>{e.preventDefault();router.go(-1);}"> <i class="bi bi-reply-all"></i></a> {{ proxy.$route.meta.theme }}
  </h1>
  <hr class="mb-4">
  <div class="row g-4 settings-section">
    <div class="app-card app-card-settings shadow-sm p-4">

      <div class="app-card-body">
        <form class="settings-form" ref="formRef">
          <div class="mb-3">
            <label for="setting-input-1" class="form-label">组件名称</label>
            <input type="text" class="form-control" v-model="form.fieldName" required>
          </div>
          <div class="mb-3">
            <label for="setting-input-1" class="form-label">组件编码</label>
            <input type="text" class="form-control" v-model="form.fieldCode" required>
          </div>
          <div class="mb-3">
            <label for="setting-input-1" class="form-label">应用模块</label>
            <input type="text" class="form-control" v-model="form.moduleName" @blur="onLoadPlugs(form.moduleName,form.fieldType,form.id||'')" required>
          </div>
          <div class="mb-3">
            <label for="setting-input-1" class="form-label">适用组件类型</label>
            <select class="form-select" v-model="form.fieldType" @change="selectChange(form.moduleName,form.fieldType,form.id||'')" required>
              <option v-for="type in types" :value="type.key">{{ type.value }}</option>
            </select>
          </div>
          <template v-if="examples[checkSelect]">
            <div class="mb-3">
              <label class="form-label" :for='`select-${checkSelect}`'>值域</label>
              <textarea rows="5" class="form-control" :class="structError&&' is-invalid '" :placeholder="`示例 ${examples[checkSelect]}`" v-model="shouldValue"
                        aria-describedby="validationShouldValue" @blur="checkInput" :id='`select-${checkSelect}`' required></textarea>
              <div id="validationShouldValue" class="invalid-feedback" v-if="structError">
                数据格式检查异常,请修改后重试
              </div>
            </div>
            <div class="mb-3" v-if="transformShouldValue">
              <label for="example-input" class="form-label">{{ form.fieldName||'示例' }}</label>
              <template v-if="checkSelect === '03'">
                <!--      数字类型          -->
                <input type="number" class="form-control" id="example-input" :value="transformShouldValue.min" :max="transformShouldValue.max" :min="transformShouldValue.min" >
              </template>
              <template v-else-if="checkSelect === '04'">
                <!--      下拉框类型          -->
                <select id="example-input" class="form-select">
                  <option v-for="(val,key,index) in transformShouldValue" :selected="index === 0" :value="key">{{ val }}</option>
                </select>
              </template>
              <template v-else-if="checkSelect === '05'">
                <!--        复选框        -->
                <div class="d-md-block ">
                  <div class="form-check form-check-inline" v-for="(value,key) in transformShouldValue">
                    <input class="form-check-input" type="checkbox" :id="`demo-check-${key}`" :value="key">
                    <label class="form-check-label" :for="`demo-check-${key}`">{{ value }}</label>
                  </div>
                </div>
              </template>
              <template v-else-if="checkSelect === '06'">
                <!--        单选框        -->
                <div class="d-md-block ">
                  <div class="form-check form-check-inline" v-for="(value,key) in transformShouldValue" >
                    <input class="form-check-input" type="radio" name="flexRadioDefault" :id="`demo-check-${key}`" :value="key">
                    <label class="form-check-label" :for="`demo-check-${key}`">{{ value }}</label>
                  </div>
                </div>
              </template>
              <template v-else-if="checkSelect === '07'">
                <!--      数字滑块类型          -->
                <input type="range" class="form-range" :value="transformShouldValue.min" :max="transformShouldValue.max" :min="transformShouldValue.min" >
              </template>
            </div>
          </template>
          <div class="mb-3" v-if="plugs && plugs.length > 0">
            <label for="setting-input-1" class="form-label">绑定插件</label>
            <div class="d-md-block ">
              <div class="form-check form-check-inline" v-for="plug in plugs" @change="notAllowEmptyCheck">
                <input class="form-check-input" type="checkbox" :id="plug.key" :value="plug.key" v-model="form.checkPlugs">
                <label class="form-check-label" :for="plug.key">{{ plug.value }}</label>
              </div>
            </div>
          </div>
          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" :disabled="form.checkPlugs && form.checkPlugs.length>0"  id="allowEmpty" v-model="form.allowEmpty">
            <label class="form-check-label" for="allowEmpty">允许为空</label>
          </div>
          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" id="settings-switch-8" v-model="form.allowDesign">
            <label class="form-check-label" for="settings-switch-8">缩略展示</label>
          </div>
          <div class="mb-3">
            <label for="setting-input-7" class="form-label">字段排序</label>
            <input type="number" class="form-control" id="setting-input-7" v-model="form.sort" required>
          </div>
          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" id="settings-switch-8" v-model="form.isEnable">
            <label class="form-check-label" for="settings-switch-8">启用</label>
          </div>
          <Transition v-if="errorMessage">
            <div class="alert alert-warning alert-dismissible fade" :class="errorMessage&&' show '" role="alert">
              <strong>错误提示!</strong> {{ errorMessage }}
            </div>
          </Transition>
          <button type="submit" class="btn app-btn-primary" @click="confirm">确认</button>
        </form>
      </div><!--//app-card-body-->

    </div><!--//app-card-->
  </div><!--//row-->
</template>

<style scoped>
:deep(.el-date-editor) {
  height: 2.5rem;
  width: 100%;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-input-border-color,var(--el-border-color)) inset;
}
</style>